<?php


namespace App\Admin\Controllers;


use App\Admin\Actions\ProductBatch\Loss;
use App\Admin\Actions\ProductBatch\View;
use App\Imports\BatchQuality\ImportQualityResult;
use App\Models\CustomerModel;
use App\Models\ProductModel;
use App\Models\ProductNameModel;
use App\Models\ProductsBatchModel;
use App\Models\SpaceModel;
use App\Models\WarehouseSiteModel;
use Encore\Admin\Actions\Action;
use Encore\Admin\Admin;
use Encore\Admin\Controllers\AdminController;
use Encore\Admin\Controllers\HasResourceActions;
use Encore\Admin\Form;
use Encore\Admin\Grid;
use Encore\Admin\Layout\Content;
use Encore\Admin\Show;
use Encore\Admin\Widgets\Table;
use Illuminate\Database\Eloquent\Collection;
use Maatwebsite\Excel\Facades\Excel;

class BatchController extends AdminController
{
    use HasResourceActions;

    protected $title = '批次';

    public function index(Content $content)
    {
        return $content
            ->header(trans('admin.Batch'))
            ->description(trans('admin.list'))
            ->body($this->grid()->render());
    }

    protected function detail($id)
    {
        $show = new Show(ProductsBatchModel::findOrFail($id));

        $show->field('batch_id', __('batch_id'));
        $show->field('product_name', __('product.product_name'));
        $show->field('variety_name', __('product.variety_name'));
        $show->field('溯源码', __('source_code'));
        $show->field('created_at', __('Created at'));
        $show->field('updated_at', __('Updated at'));

        return $show;
    }
    /**
     * Make a grid builder.
     *
     * @return Grid
     */
    protected function grid()
    {
        $grid = new Grid(new ProductsBatchModel());
        $grid->model()->orderBy('batch_id', 'desc');
        $grid->column('product.product_name', '商品名');
        $grid->column('product.variety_name', '产品种类');
        $grid->column('source_code', '溯源码')->copyable();
        $grid->column('auth_type', '认证类型')->display(function ($data) {
            $str = '';
            $arr = explode(',', $data);
            foreach ($arr as $k => $v) {
                if ($k > 0) {
                    $str .= ',' . ProductsBatchModel::MAP_AUTH[$v];
                } else {
                    $str .= ProductsBatchModel::MAP_AUTH[$v];
                }
            }
            return $str;
        });
        $grid->column('number_unit', '收获数量')->display(function () {
            return $this['number'] . ProductsBatchModel::MAP_UNIT[$this['unit']];
        });
        $grid->column('sale_unit', '已销售')->display(function () {
            return $this['sale_number'] . ProductsBatchModel::MAP_UNIT[$this['unit']];
        });

        $grid->column('loss_number_unit', '损耗')->display(function () {
            return $this['loss_number'] . ProductsBatchModel::MAP_UNIT[$this['unit']];
        })->modal('损耗记录', function ($model) {

            $loss = $model->productLoss()->take(100)->orderBy('loss_id', 'desc')->get()->map(function ($loss) {
                return $loss->only(['loss_id', 'loss_type', 'loss_num', 'remark', 'created_at']);
            });
            return new Table(['ID', '报损类型', '报损数量', '报损原因', '报损时间'], $loss->toArray());
        });

        $grid->column('stock_unit', '库存')->display(function () {
            return $this['stock'] . ProductsBatchModel::MAP_UNIT[$this['unit']];
        });

        $grid->column('source', '产品来源')->using(ProductsBatchModel::MAP_SOURCE);

        $grid->column('quality_result', '质检情况')->using(ProductsBatchModel::MAP_QUALITY)
            ->modal('质检报告', function ($model) {
                $loss = $model->Quality()->take(1)->get()->map(function ($loss) {
                    return $loss->only([
                        'no',
                        'product_name',
                        'test_name',
                        'test_result1',
                        'test_result',
                        'start_test_time',
                        'test_compony',
                        'test_user',
                        'test_time',
                        'channel_id',
                        'test_device'
                    ]);
                });
                return new Table(['序号', '产品名称', '检测项目名称', '检测结果（合格/不合格）', '抑制率/检测项目结论', '送检时间', '检测机构', '检测员', '检测时间', '通道号', '检测仪品牌名'], $loss->toArray());
            });;
        $grid->column('receive_time', '收获时间')->sortable();

        $grid->actions(function ($action) {
            $action->disableView();
            $action->add(new Loss());
//            $action->add(new View());
        });

        $grid->filter(function ($filter) {
//            $filter->column(1 / 2, function ($filter) {
//                $filter->where(function ($query) {
//                    $query->where('product.product_name', 'like', "%{$this->input}%");
//                }, '关键词')->placeholder('产品名');
//            });

            $filter->column(1 / 2, function ($filter) {
                $filter->where(function ($query) {
                    $query->where('source_code', '=', $this->input);
                }, '溯源码')->placeholder('溯源码');
            });
        });


        return $grid;
    }

    protected function editForm()
    {
        $form = new Form(new ProductsBatchModel());
        $form->select('product_id', '产品名称')->options(function ($id) {
            return ProductModel::withTrashed()->pluck('product_name', 'product_id')->toArray();
        })->required()->readOnly();

        $form->hidden('batch_id');
        $form->select('unit', '单位')->options(ProductsBatchModel::MAP_UNIT)
            ->default(1)->rules('required')->readOnly();
        $form->text('number', '收货数量')->rules('required|regex:/^\d+$/', [
            'regex' => '收获数量必须为数字',
        ]);

        $form->select('source', '来源')->options(ProductsBatchModel::MAP_SOURCE)
            ->default(1)->rules('required')->readOnly();

        $form->select('customer_id', '上游企业名称')->options(function ($name) {
            return CustomerModel::withTrashed()->pluck('name', 'customer_id')->toArray();
        })->default(0)->readOnly();

        $form->select('base_id', '基地名称')->options(function ($name) {
            return SpaceModel::pluck('name', 'base_id')->toArray();
        })->default(0)->readOnly();

        $form->datetime('receive_time', '收获时间')->format('YYYY-MM-DD')
            ->default(date('YYYY-MM-DD', time()))->readOnly();

        $form->radio('quality_type', '质检情况')->default(1)
            ->options(ProductsBatchModel::MAP_QUALITY)->readOnly();

        $form->file('quality_file', '质检结果表格导入')->rules('mimes:xlsx,xls')->hidePreview()->uniqueName();

        $form->mediaManagerSelect('quality_image', '质检结果图片导入');

        $form->switch('quality_result', '质检状态')->default('1')->states([
            'on' => ['value' => 1, 'text' => '合格', 'color' => 'success'],
            'off' => ['value' => 0, 'text' => '不合格', 'color' => 'danger'],
        ]);

        $form->checkbox('auth_type', '认证情况')
            ->options([1 => '无公害农产品', 2 => '有机视频', 3 => '绿色食品', 4 => '农产品地理标识']);

        $form->mediaManagerSelect('image', '图片');

        $form->mediaManagerSelect('video', '视频');

        $form->listbox('WarehouseSite', '选择仓库')->options(function () use ($form) {
            $site = WarehouseSiteModel::with(['WarehouseShelf.WarehouseArea.Warehouse'])->get()->map(function ($site) {
                $shelf_name = $site['WarehouseShelf']['shelf_name'];
                $area_name = $site['WarehouseShelf']['WarehouseArea']['area_name'];
                $warehouse_name = $site['WarehouseShelf']['WarehouseArea']['Warehouse']['warehouse_name'];
                $site['site_name'] = $warehouse_name . '-区域' . $area_name . '-货架' . $shelf_name . '-货位' . $site['site_name'];
                return $site;
            });

            return $site->pluck('site_name', 'site_id')->toArray();
        });
        $form->tools(function (Form\Tools $tools) {
            $tools->disableDelete();
            $tools->disableView();
        });
        $form->display('created_at', 'Created At');
        $form->display('updated_at', 'Updated At');

        Admin::script("$(function(){
            if($('select.source').val()=='1'){
             $('label[for=customer_id]').parent().hide();
                $('label[for=base_id]').parent().show();
            }else if($('select.source').val()=='1'){
                $('label[for=base_id]').parent().hide();
                $('label[for=customer_id]').parent().show();
            }
        })");
        Admin::script("$('select.source').on('change',function(){
            if($(this).val()=='1'){
                $('label[for=customer_id]').parent().hide();
                $('label[for=base_id]').parent().show();
            }else if($(this).val()=='2'){
                $('label[for=base_id]').parent().hide();
                $('label[for=customer_id]').parent().show();
            }
        })");

        return $form;
    }

    /**
     * Make a form builder.
     *
     * @return Form
     */
    protected function form()
    {
        $form = new Form(new ProductsBatchModel());


        $form->select('product_id', '产品名称')->options(function ($id) {
            return ProductModel::pluck('product_name', 'product_id')->toArray();
        })->required();

        $form->hidden('batch_id');
        $form->select('unit', '单位')->options(ProductsBatchModel::MAP_UNIT)
            ->default(1)->rules('required');
        $form->text('number', '收货数量')->rules('required|regex:/^\d+$/', [
            'regex' => '收获数量必须为数字',
        ]);

        $form->select('source', '来源')->options(ProductsBatchModel::MAP_SOURCE)
            ->default(1)->rules('required');

        $form->select('customer_id', '上游企业名称')->options(function ($name) {
            return CustomerModel::pluck('name', 'customer_id')->toArray();
        })->default(0);

        $form->select('base_id', '基地名称')->options(function ($name) {
            return SpaceModel::pluck('name', 'base_id')->toArray();
        })->default(0);

        $form->datetime('receive_time', '收获时间')->format('YYYY-MM-DD')
            ->default(date('YYYY-MM-DD', time()));

        $form->radio('quality_type', '质检情况')->default(1)
            ->options(ProductsBatchModel::MAP_QUALITY);

        $form->file('quality_file', '质检结果表格导入')->rules('mimes:xlsx,xls')->hidePreview()->uniqueName();

        $form->mediaManagerSelect('quality_image', '质检结果图片导入');

        $form->switch('quality_result', '质检状态')->default('1')->states([
            'on' => ['value' => 1, 'text' => '合格', 'color' => 'success'],
            'off' => ['value' => 0, 'text' => '不合格', 'color' => 'danger'],
        ]);

        $form->checkbox('auth_type', '认证情况')
            ->options([1 => '无公害农产品', 2 => '有机视频', 3 => '绿色食品', 4 => '农产品地理标识']);

        $form->mediaManagerSelect('image', '图片');

        $form->mediaManagerSelect('video', '视频');

        $form->listbox('WarehouseSite', '选择仓库')->options(function () {
            $site = WarehouseSiteModel::has('ProductBatch', '=', 0)->with(['WarehouseShelf.WarehouseArea.Warehouse'])->get()->map(function ($site) {
                $shelf_name = $site['WarehouseShelf']['shelf_name'];
                $area_name = $site['WarehouseShelf']['WarehouseArea']['area_name'];
                $warehouse_name = $site['WarehouseShelf']['WarehouseArea']['Warehouse']['warehouse_name'];
                $site['site_name'] = $warehouse_name . '-区域' . $area_name . '-货架' . $shelf_name . '-货位' . $site['site_name'];
                return $site;
            });

            return $site->pluck('site_name', 'site_id')->toArray();
        });

        $form->tools(function (Form\Tools $tools) {
            $tools->disableDelete();
            $tools->disableView();
        });
        $form->display('created_at', 'Created At');
        $form->display('updated_at', 'Updated At');

        $form->saved(function (Form $form) {
            if ($form->quality_file) {
                Excel::import(new ImportQualityResult($form->batch_id), $form->quality_file);
            }

        });

        Admin::script("$(function(){
            if($('select.source').val()=='1'){
             $('label[for=customer_id]').parent().hide();
                $('label[for=base_id]').parent().show();
            }else if($('select.source').val()=='1'){
                $('label[for=base_id]').parent().hide();
                $('label[for=customer_id]').parent().show();
            }
        })");
        Admin::script("$('select.source').on('change',function(){
            if($(this).val()=='1'){
                $('label[for=customer_id]').parent().hide();
                $('label[for=base_id]').parent().show();
            }else if($(this).val()=='2'){
                $('label[for=base_id]').parent().hide();
                $('label[for=customer_id]').parent().show();
            }
        })");
        return $form;
    }

    /**
     * Create interface.
     *
     * @return Content
     */
    public function create(Content $content)
    {
        return $content
            ->header(trans('admin.Batch'))
            ->description(trans('admin.create'))
            ->body($this->form());
    }

    /**
     * Edit interface.
     *
     * @param $id
     *
     * @param Content $content
     * @return Content
     */
    public function edit($id, Content $content)
    {
        return $content
            ->header(trans('admin.Batch'))
            ->description(trans('admin.edit'))
            ->body($this->editForm()->edit($id));
    }
}
